package com.kyxx.topics.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.activity.MessageReplyActivity;
import com.kyxx.topics.bean.CommentBean;
import com.kyxx.topics.bean.MessageCommentBean;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.TimeUtils;
import com.kyxx.topics.utils.ToastUtils;
import com.loopj.android.http.RequestParams;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.BaseRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.wang.avi.AVLoadingIndicatorView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import okhttp3.Call;
import okhttp3.Response;

public class MessageCommentFragment extends Fragment {
    private RelativeLayout rl_progress;
    private ProgressBar avi;
    private LinearLayout ll_reload;
    private LinearLayout ll_no;
    private PtrClassicFrameLayout ptrv;
    private SwipeMenuListView smlv;
    private List<MessageCommentBean> messageCommentBeanList = new ArrayList<>();
    MessageCommentAdapter messageCommentAdapter;
    private int pageSize = 1;
    private int countSize = 10;
    private int lastVisiblePosition;
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
            .cacheOnDisk(true)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .showImageOnFail(R.mipmap.icon_user_default)
            .showImageOnLoading(R.mipmap.icon_user_default)
            .showImageForEmptyUri(R.mipmap.icon_user_default)
            .build();
    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    rl_progress.setVisibility(View.GONE);
                    break;
                case 2:
                    rl_progress.setVisibility(View.VISIBLE);
                    avi.setVisibility(View.GONE);
                    ll_reload.setVisibility(View.VISIBLE);
                    ll_no.setVisibility(View.GONE);
                    break;
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        messageCommentAdapter.notifyDataSetChanged();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_message_comment, container, false);
        ptrv = (PtrClassicFrameLayout) view.findViewById(R.id.ptrv);
        rl_progress = (RelativeLayout) view.findViewById(R.id.rl_progress);
        rl_progress = (RelativeLayout) view.findViewById(R.id.rl_progress);
        avi = (ProgressBar) view.findViewById(R.id.avi);
        ll_no = (LinearLayout) view.findViewById(R.id.ll_no);
        ll_reload = (LinearLayout) view.findViewById(R.id.ll_reload);
        ll_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pageSize = 1;
                getData(Constants.INITDATA);
            }
        });
        smlv = (SwipeMenuListView) view.findViewById(R.id.smlv);
        smlv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (lastVisiblePosition == smlv.getLastVisiblePosition())
                    return;
                lastVisiblePosition = smlv.getLastVisiblePosition();
                Log.e("topic", lastVisiblePosition + "onScroll" + smlv.getCount());
                if (lastVisiblePosition == smlv.getCount() - 2 && smlv.getCount() >= countSize) {
//                    pageSize++;
//                    getData(Constants.LOADMORE);
                }
            }
        });
        messageCommentAdapter = new MessageCommentAdapter();
        smlv.setAdapter(messageCommentAdapter);
        getData(Constants.INITDATA);
        return view;
    }

    private void getData(final int type) {
        HttpParams params = new HttpParams();
        params.put("uid", BaseApp.getModel().getId());
        params.put("p", pageSize);
        params.put("rows", countSize);
        String cacheKey = "notify&uid=" + BaseApp.getModel().getId() + "p=" + pageSize + "&rows=" + countSize;
        OkGoRequest.post(UrlUtils.NOTIFY, getActivity(), cacheKey, CacheMode.REQUEST_FAILED_READ_CACHE, params, new StringCallback() {
            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                rl_progress.setVisibility(View.VISIBLE);
                avi.setVisibility(View.VISIBLE);
                ll_reload.setVisibility(View.GONE);
            }

            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onCacheError(Call call, Exception e) {
                super.onCacheError(call, e);
                handler.sendEmptyMessageDelayed(2, Constants.DELAYTIMES);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                rl_progress.setVisibility(View.GONE);
                try {
                    JSONObject result = new JSONObject(s);
                    switch (type) {
                        case Constants.INITDATA:
                            messageCommentBeanList = JSON.parseArray(result.get("data").toString(), MessageCommentBean.class);
                            break;
                        case Constants.LOADMORE:
                            messageCommentBeanList.addAll(JSON.parseArray(result.get("data").toString(), MessageCommentBean.class));
                    }
                    messageCommentAdapter.notifyDataSetChanged();
                    lastVisiblePosition = smlv.getLastVisiblePosition();
                    if (messageCommentBeanList==null||messageCommentBeanList.size() == 0){
                        rl_progress.setVisibility(View.VISIBLE);
                        ll_no.setVisibility(View.VISIBLE);
                        ll_reload.setVisibility(View.GONE);
                        avi.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    rl_progress.setVisibility(View.VISIBLE);
                    ll_no.setVisibility(View.VISIBLE);
                    ll_reload.setVisibility(View.GONE);
                    avi.setVisibility(View.GONE);
                }
            }
        });
    }

    class MessageCommentAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return messageCommentBeanList == null ? 0 : messageCommentBeanList.size();
        }

        @Override
        public Object getItem(int i) {
            return messageCommentBeanList == null ? null : messageCommentBeanList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return messageCommentBeanList == null ? 0 : i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = View.inflate(getActivity(), R.layout.item_message_comment, null);
                holder.iv_avatar = (ImageView) view.findViewById(R.id.iv_avatar);
                holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
                holder.tv_content = (TextView) view.findViewById(R.id.tv_content);
                holder.tv_time = (TextView) view.findViewById(R.id.tv_time);
                holder.tv_status = (TextView) view.findViewById(R.id.tv_status);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            final CommentBean commentBean = messageCommentBeanList.get(i).getComment();
            if (!TextUtils.isEmpty(commentBean.getAvatar())) {
                imageLoader.displayImage(commentBean.getAvatar(), holder.iv_avatar, options);
            } else {
                imageLoader.displayImage("", holder.iv_avatar, options);
            }
            holder.tv_name.setText(commentBean.getNickname());
            holder.tv_content.setText(commentBean.getContent());
            holder.tv_time.setText(TimeUtils.milliseconds2String(Long.valueOf(commentBean.getAddtime()) * 1000, new SimpleDateFormat("MM-dd HH:mm")));
            if ("0".equals(messageCommentBeanList.get(i).getStatus())) {
                holder.tv_status.setText("未读");
            } else {
                holder.tv_status.setText("已读");
            }
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), MessageReplyActivity.class);
                    intent.putExtra("id", commentBean.getPid());
                    getActivity().startActivityForResult(intent, 1);
                    if ("0".equals(messageCommentBeanList.get(i).getStatus())) {
                        setStatus(messageCommentBeanList.get(i).getId());
                        messageCommentBeanList.get(i).setStatus("1");
                    }
                }
            });
            return view;
        }
    }

    class ViewHolder {
        private ImageView iv_avatar;
        private TextView tv_name;
        private TextView tv_content;
        private TextView tv_time;
        private TextView tv_status;
    }

    private void setStatus(String id) {
        RequestParams params = new RequestParams();
        params.put("id", id);
        RestClient.post(UrlUtils.SETSTATUS, params, getActivity(), new ResponseListener(getActivity(), false) {
            @Override
            public void success(int arg0, Header[] arg1, JSONObject result) {
            }
        });
    }
}
